import { Store } from 'vuex'
import { Route } from 'vue-router'
import { Middleware, Context } from '@nuxt/types'

import { ModuleEnum } from '@/enums/module.enum'
import { TOGGLE_MODULE } from '@/enums/mutation-types'
import { AppConfig } from '@/types/app-config'
import { LoginStatusEnum } from '@/enums/login-status.enum'

const routeAdapter = (redirect: (path: string) => void, store: Store<any>, route: Route) => {
  if (route.path === '/') {
    return redirect('/console/dashboard')
  }
  if (route.path.startsWith('/monitor')) {
    store.commit('app/' + TOGGLE_MODULE, ModuleEnum.Monitor)
  } else if (route.path.startsWith('/maintain')) {
    store.commit('app/' + TOGGLE_MODULE, ModuleEnum.Maintain)
  } else if (route.path.startsWith('/settings')) {
    store.commit('app/' + TOGGLE_MODULE, ModuleEnum.Settings)
  } else if (route.path.startsWith('/console')) {
    store.commit('app/' + TOGGLE_MODULE, ModuleEnum.Console)
  }
}

const moduleAdapterMiddleware: Middleware = async ({
  isHMR,
  store,
  route,
  redirect,
  app,
  env
}: Context) => {
  if (isHMR) {
    return
  }
  const appConfig = env as AppConfig
  const paths: string[] = appConfig.ignoreAuthRoutes.split(',')
  if (!paths.includes(route.path)) {
    const token = app.$cookies.get<string>(appConfig.cookieToken)
    if (token) {
      const authStatus = store.state.user.auth.status as LoginStatusEnum
      if (LoginStatusEnum.Logout === authStatus) {
        const isAuth = await store.dispatch('user/tokenAuthentication')
        if (isAuth) {
          routeAdapter(redirect, store, route)
        } else {
          await store.dispatch('user/clearUserState')
          return redirect('/login')
        }
      } else {
        routeAdapter(redirect, store, route)
      }
    } else {
      await store.dispatch('user/clearUserState')
      return redirect('/login')
    }
  }
}

export default moduleAdapterMiddleware
